package com.liyunc.demo.comp.id.generate.service;

import com.liyunc.demo.comp.common.db.IdentifiedObject;
import com.liyunc.demo.comp.common.db.JpaIdStrategy;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.persistence.TableGenerator;
import java.io.Serializable;
import java.util.Objects;

/**
 * @author liyuncong
 * @version 1.0
 * @file SnowFlakeIdGenerator.java
 * @brief SnowFlakeIdGenerator
 * @details SnowFlakeIdGenerator
 * @date 2022-04-08
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2022-04-08                  liyuncong          Created
 */
@Component
@TableGenerator(name = JpaIdStrategy.SNOW_FLAKE)
public class SnowFlakeIdGenerator implements IdentifierGenerator {

    @Autowired
    private SingIdGenerator singIdGenerator;

    @Override
    public boolean supportsJdbcBatchInserts() {
        return true;
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object)
        throws HibernateException {
        if ((object instanceof IdentifiedObject identifiedObject)
            && Objects.nonNull(identifiedObject.getId())) {
            return identifiedObject.getId();
        }
        return singIdGenerator.snowFlake();
    }
}
